﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Simulator
{
    class WaterMonitor
    {
        public double Level { get; private set; }
        private object _locker;

        public event Message LevelMsg;
        public event Message RainMsg;
        public event Message DrainMsg;

        public WaterMonitor()
        {
            Level = 0;
            _locker = new object();
        }

        public void Enqueue(double value)
        {
            lock (_locker)
            {
                RainMsg(value);
                Level += value;
                LevelMsg(Level);
                Monitor.Pulse(_locker);
            }
        }
        public void Dequeue(double value)
        {
            lock (_locker)
            {
                while (Level <= 0)
                    Monitor.Wait(_locker);
                value = Level > 0 && Level >= value ? value : Level; //if there's water, find how much to drain, o
                Level = Level > 0 && Level >= value ? Level - value : 0; //new level dependant on drain, o
                DrainMsg(value);
                LevelMsg(Level);
            }
        }
    }
}
